package cn.junki.sparkbigmodeldemo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.junki.sparkbigmodeldemo.entity.dto.SparkBigModelChatDTO;
import cn.junki.sparkbigmodeldemo.entity.dto.SparkBigModelChatMessage;
import cn.junki.sparkbigmodeldemo.entity.request.SparkBigModelChatRequest;
import cn.junki.sparkbigmodeldemo.entity.vo.SparkBigModelChatVO;
import cn.junki.sparkbigmodeldemo.listener.SparkBigModelWebSocketListener;
import cn.junki.sparkbigmodeldemo.properties.SparkBigModelProperties;
import cn.junki.sparkbigmodeldemo.service.SparkBigModelService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Consumer;

/**
 * 星火大模型业务实现类
 *
 * @author Junki
 * @date 2023-09-28 10:43:10
 */
@Slf4j
@Service
public class SparkBigModelServiceImpl implements SparkBigModelService {

    @Resource
    private SparkBigModelProperties sparkBigModelProperties;

    @Override
    public void chat(SparkBigModelChatDTO sparkBigModelChatDTO, Consumer<SparkBigModelChatVO> onMessageCallBack) {

        // 限制上下文长度
        sparkBigModelChatDTO.setMessageList(this.limitContextLength(sparkBigModelChatDTO.getMessageList()));

        // 封装大模型请求参数
        SparkBigModelChatRequest sparkBigModelChatRequest = SparkBigModelChatRequest.builder()
                .header(
                        SparkBigModelChatRequest.Header.builder()
                                .app_id(sparkBigModelProperties.getAppId())
                                .build()
                )
                .parameter(
                        SparkBigModelChatRequest.Parameter.builder()
                                .chat(
                                        SparkBigModelChatRequest.Chat.builder()
                                                .domain(sparkBigModelProperties.getDomain())
                                                .max_tokens(4096)
                                                .build()
                                )
                                .build()
                )
                .payload(
                        SparkBigModelChatRequest.Payload.builder()
                                .message(
                                        SparkBigModelChatRequest.Message.builder()
                                                .text(BeanUtil.copyToList(sparkBigModelChatDTO.getMessageList(), SparkBigModelChatRequest.Text.class))
                                                .build()
                                )
                                .build()
                )
                .build();

        // 使用okhttp请求大模型接口，并设置响应监听
        OkHttpClient client = new OkHttpClient.Builder().build();

        // 星火助手api地址
        String apiUrl = sparkBigModelProperties.getAssistantChatUrl().replace("{assistantsId}", sparkBigModelProperties.getOldManAssistantId());
        // 星火通用大模型api地址
        // String apiUrl = sparkBigModelProperties.getChatUrl();

        String authUrl;
        try {
            authUrl = getAuthUrl(apiUrl, sparkBigModelProperties.getAppKey(), sparkBigModelProperties.getAppSecret());
        } catch (Exception e) {
            log.error("鉴权url生成失败", e);
            throw new RuntimeException(e);
        }
        Request request = new Request.Builder().url(authUrl).build();
        client.newWebSocket(request, new SparkBigModelWebSocketListener(sparkBigModelChatRequest, onMessageCallBack, null));

    }

    /**
     * 限制历史消息长度
     */
    private List<SparkBigModelChatMessage> limitContextLength(List<SparkBigModelChatMessage> messageList) {
        if (CollUtil.isEmpty(messageList)) {
            return messageList;
        }

        // 最大长度
        int maxLength = sparkBigModelProperties.getContextMaxLength();

        // 当前历史消息总长度
        int lengthTotal = messageList.stream()
                .mapToInt(medicalBigModelChatMessage -> StrUtil.isBlank(medicalBigModelChatMessage.getContent()) ? 0 : medicalBigModelChatMessage.getContent().length())
                .sum();

        // 如果超长则移除第一条消息
        while (lengthTotal > maxLength && !messageList.isEmpty()) {
            SparkBigModelChatMessage removedMessage = messageList.remove(0);
            lengthTotal -= StrUtil.isBlank(removedMessage.getContent()) ? 0 : removedMessage.getContent().length();
        }

        return messageList;
    }

    // 鉴权方法
    private String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        hostUrl = hostUrl.replace("ws://", "http://").replace("wss://", "https://");
        URL url = new URL(hostUrl);
        // 时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        // 拼接
        String preStr = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                "GET " + url.getPath() + " HTTP/1.1";
        // SHA256加密
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // Base64加密
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        // 拼接
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().//
                addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).//
                addQueryParameter("date", date).//
                addQueryParameter("host", url.getHost()).//
                build();

        return httpUrl.toString();
    }

}
